<template>
  <page-container>
    <!-- 管理员可以选择查看某个媒体方的数据 -->
    <a-select
      v-if="userState.role === 'manager'"
      v-model:value="selectedMedium"
      class="medium-selector"
      allow-clear
      :options="mediumOptions"
      placeholder="选择媒体方查看其数据"
      @change="handleMediumChange"
    />

    <block-wrapper title="预估收入">
      <a-row justify="center">
        <a-col :span="6">
          <a-statistic
            class="tc"
            title="昨日收入 (元)"
            :value="mediaIndex.yesterday_income"
            style="margin-right: 50px"
          />
        </a-col>
        <a-col :span="6">
          <a-statistic class="tc" title="本月收入 (元)" :precision="2" :value="mediaIndex.month_income" />
        </a-col>
        <a-col :span="6">
          <a-statistic class="tc" title="本年收入 (元)" :precision="2" :value="mediaIndex.year_income" />
        </a-col>
      </a-row>
    </block-wrapper>

    <a-row style="margin-top: 18px; margin-bottom: 18px" :gutter="10">
      <a-col :span="12">
        <block-wrapper title="千次展示收入">
          <line-chart style="height: 300px" :category="thousandCategory" :series-data="thousandSeriesData" />
        </block-wrapper>
      </a-col>

      <a-col :span="12">
        <block-wrapper title="流量漏斗">
          <funnel-chart style="height: 300px" :series-data="funnelData" />
        </block-wrapper>
      </a-col>
    </a-row>

    <block-wrapper title="广告数据" style="position: relative">
      <line-chart style="height: 300px" :category="mediaHistoryCategory" :series-data="mediaHistory" />
      <a-range-picker v-model:value="rangeDate" :disabled-date="disabledDate" class="range-picker" />
    </block-wrapper>
  </page-container>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { getMediaHistory, getMediaIndex, type IMediaIndex } from '@/api/dataStatistic';
import type { IFunnelSeriesData, ILineSeriesData, IOption } from '@/types';
import { getMedias } from '@/api/medium';
import { useUserStore } from '@/store';

const userState = useUserStore();

const mediumOptions = ref<IOption[]>([]);
const selectedMedium = ref();

const mediaIndex = ref<IMediaIndex>({
  yesterday_income: 0,
  month_income: 0,
  year_income: 0,
});
const thousandCategory = ref<string[]>([]);
const thousandSeriesData = ref<number[][]>([]);

const funnelData = ref<IFunnelSeriesData[]>([]);

const setMediaOptions = async () => {
  const data = await getMedias({ page: 1, page_size: 100 });
  mediumOptions.value = data.data.list.map(({ id, name }) => ({ label: name, value: id }));
};
setMediaOptions();

//const getPercent = (value: number, base: number) => (value / base) * 100;
const getPercent = (value: number, base: number) => {
  // 检查base是否为0，或者value、base是否为非数字
  if (base === 0 || isNaN(value) || isNaN(base)) {
    return 0;
  }
  // 计算百分比并保留两位小数，结果为字符串
  const percentString = ((value / base) * 100).toFixed(2);

  // 如果你需要结果作为数值类型，可以使用parseFloat转换回数值
  return parseFloat(percentString);
};

const updateMediaIndex = () => {
  getMediaIndex(selectedMedium.value).then(res => {
    if (Array.isArray(res.data.thounds_show)) {
      const revenueData: number[] = [];
      res.data.thounds_show.forEach(item => {
        thousandCategory.value.push(item.date);
        revenueData.push(item.revenue);
      });

      thousandSeriesData.value = [revenueData];
    }

    mediaIndex.value = res.data;

    const { click = 0, show = 0, return: returnValue = 0, request = 0 } = res.data;
    const maxValue = Math.max(click, show, returnValue, request);

    funnelData.value = [
      { value: getPercent(click, maxValue), name: '点击量' },
      { value: getPercent(show, maxValue), name: '曝光量' },
      { value: getPercent(returnValue, maxValue), name: '广告位返回量' },
      { value: getPercent(request, maxValue), name: '广告位请求量' },
    ];
  });
};

updateMediaIndex();

const rangeDate = ref<[dayjs.Dayjs, dayjs.Dayjs]>([dayjs().subtract(7, 'day'), dayjs().subtract(1, 'day')]);
const disabledDate = (current: dayjs.Dayjs) => {
  // 不能选择今天以及今天之后的日期
  return current.diff(dayjs(), 'day') >= 0;
};
const mediaHistoryCategory = computed(() => {
  // 获取两个日期之间的日期
  const start = rangeDate.value[0].format('YYYY-MM-DD');
  const end = rangeDate.value[1].format('YYYY-MM-DD');
  const diff = dayjs(end).diff(dayjs(start), 'day');
  const result = [];
  for (let i = 0; i <= diff; i++) {
    result.push(dayjs(start).add(i, 'day').format('YYYY-MM-DD'));
  }
  return result;
});
const mediaHistory = ref<ILineSeriesData>([]);

const updateMediaHistory = () => {
  // eslint-disable-next-line prefer-const
  let [start, end] = rangeDate.value.map(d => d.unix());
  // 如果 start 和 end 相等，给 end 加上一天的时间量（86400秒）
  if (start === end) {
    end += 86400 - 1; // 86400秒等于一天
  }
  getMediaHistory(start, end, selectedMedium.value).then(res => {
    const arr: { show: number; revenue: number }[] = res.data.data;
    const displayData: ILineSeriesData[number] = { name: '展示', data: [] };
    const revenueData: ILineSeriesData[number] = { name: '收入', data: [] };

    arr.forEach(item => {
      displayData.data.push(item.show);
      revenueData.data.push(item.revenue);
    });

    mediaHistory.value = [displayData, revenueData];
  });
};
updateMediaHistory();

watch(rangeDate, () => {
  updateMediaHistory();
});

const handleMediumChange = () => {
  updateMediaIndex();
  updateMediaHistory();
};
</script>

<style lang="less" scoped>
.medium-selector {
  position: absolute;
  right: 24px;
  top: 10px;
  width: 240px;
}

.range-picker {
  position: absolute;
  top: 20px;
  right: 20px;
}
</style>
